//
//  NewFoodViewController.m
//  FoodFamily
//
//  Created by dlios on 15-6-20.
//  Copyright (c) 2015年 guoBang. All rights reserved.
//

#import "NewFoodViewController.h"
#import "AFNGetDataValue.h"
#import "FoodCityModle.h"
#import "FoodCitySql.h"
@interface NewFoodViewController ()

@end

@implementation NewFoodViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //打开数据库
    [[FoodCitySql sharDataHandel]OpenDB];
    //创建列表
    [[FoodCitySql sharDataHandel]creatTable];
    self.nextPage = 1;
    self.navigationController.navigationBar.backgroundColor = [UIColor whiteColor];

    
    //改变navigationBar的背景颜色和标题颜色
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"690EFC73-E213-4C10-9FF7-CCE713AC7BC1.png"] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor whiteColor],NSFontAttributeName:[UIFont systemFontOfSize:19.0]}];
    
    
    
//        self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:129/255.0 green:197/255.0 blue:198/255.0 alpha:1.0];


    
    self.view.backgroundColor = [UIColor clearColor];
    UICollectionViewFlowLayout *collectionVFLayout = [[UICollectionViewFlowLayout alloc]init];
    
    
    if (  WIDTH >= 375) {
        collectionVFLayout.itemSize = CGSizeMake((WIDTH - 40)/2, HEIGHT - 400);
        collectionVFLayout.minimumInteritemSpacing =20;
        collectionVFLayout.minimumLineSpacing = 10;
        collectionVFLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
        collectionVFLayout.sectionInset =UIEdgeInsetsMake(15,10, 1,10);

 
    }else if (WIDTH< 375){
    
        collectionVFLayout.itemSize = CGSizeMake(280,240);
        collectionVFLayout.minimumInteritemSpacing =20;
        collectionVFLayout.minimumLineSpacing = 10;
        collectionVFLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
        collectionVFLayout.sectionInset =UIEdgeInsetsMake(15,10, 1,10);


    }
    
//   if (WIDTH>414 ) {
//    
//        collectionVFLayout.itemSize = CGSizeMake((WIDTH - 40)/3, HEIGHT - 650);
//        collectionVFLayout.minimumInteritemSpacing =10;
//        collectionVFLayout.minimumLineSpacing = 5;
//        collectionVFLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
//        collectionVFLayout.sectionInset =UIEdgeInsetsMake(15,10, 1,10);
//    
//    }
//
    
    self.collectV = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-20 - 44 - 49) collectionViewLayout:collectionVFLayout];
    self.collectV.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.collectV];
    [self.collectV release];
    self.collectV.delegate = self;
    self.collectV.dataSource = self;
    [self.collectV registerClass:[NewFoodCollectionViewCell class] forCellWithReuseIdentifier:@"reuser"];
    self.array = [NSMutableArray array];
    [self getInFo];
        //刷新

    self.MBHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.MBHUD.labelText = @"正在加载中";
    [self.MBHUD show:YES];
    [self.collectV.header beginRefreshing];
    [self headerRefesh];
    [self footerRefesh];


    
    
}

-(void)reloadValue {
    self.MBHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.MBHUD.labelText = @"正在加载中...";
    [self.MBHUD show:YES];
    [self getInFo];
    
}


#warning   下拉刷新
-(void)headerRefesh {
    self.collectV.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.nextPage = 1;
        self.downUpdata = YES;
        
        //让菊花旋转起来
        self.MBHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        self.MBHUD.labelText = @"正在加载中...";
        [self.MBHUD show:YES];
        [self getInFo];
        
        // 刷新表格
        [self.collectV reloadData];
        
        // 拿到当前的下拉刷新控件，结束刷新状态
        
        
        
    }];
    
}
#warning 上拉加载
-(void)footerRefesh {
    
    self.collectV.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        
        
        self.nextPage++;
        self.downUpdata = NO;
        self.MBHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        self.MBHUD.labelText = @"正在加载中...";
        [self.MBHUD show:YES];
        [self getInFo];
        
        // 刷新表格
        [self.collectV reloadData];
        
    }];
    
}

-(void)getInFo{

    if (self.nextPage == 1) {
        
       self.array = [[FoodCitySql sharDataHandel]selectAllFoodCity];
    }

    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *location = [userDefaults objectForKey:@"city"];
    
    NSString *string = [NSString stringWithFormat:@"http://api.meishixing.com/picture/picturelist/last/page=%lu&city_id=%@&session_id=00001227993a5661b25da19c79c2a7c9a6affc",self.nextPage, location];

    [AFNGetDataValue getDataAFN:string block:^(NSMutableDictionary *dataDic) {

        if (dataDic == nil) {
            [self.collectV.footer endRefreshing];
            [self.collectV.header endRefreshing];
            [self.MBHUD hide:YES];
        }
        else{
            if (self.nextPage == 1) {
                [[FoodCitySql sharDataHandel]dropTable];
                [[FoodCitySql sharDataHandel]creatTable];
                
            }
            
            //如果是下拉
            if (self.nextPage == 1) {
                
                [self.array removeAllObjects];
                
            }
            NSMutableArray *array = [dataDic objectForKey:@"result"];
            for (NSMutableDictionary *dic in array) {
                FoodCityModle *foodModel = [[FoodCityModle alloc]init];
                foodModel.comment = [dic objectForKey:@"comment"];
                foodModel.user_image = [dic objectForKey:@"user_image"];
                foodModel.city_id = [dic objectForKey:@"city_id"];
                foodModel.image_height  =  [dic objectForKey:@"image_height"];
                foodModel.want_it_total = [dic objectForKey:@"want_it_total"];
                foodModel.address = [dic objectForKey:@"address"];
                foodModel.city_name = [dic objectForKey:@"city_name"];
                foodModel.picture_id = [dic objectForKey:@"picture_id"];
                foodModel.place_name = [dic objectForKey:@"place_name"];
                foodModel.picture_url = [dic objectForKey:@"picture_url"];
                foodModel.image_width = [dic objectForKey:@"image_width"];
                foodModel.pv_count = [dic objectForKey:@"pv_count"];
                foodModel.user_name = [dic objectForKey:@"user_name"];
                foodModel.food_name = [dic objectForKey:@"food_name"];
                foodModel.level_title = [dic objectForKey:@"level_title"];
                foodModel.user_id = [dic objectForKey:@"user_id"];
                foodModel.lng = [[dic objectForKey:@"lng"]stringValue];
                foodModel.lat = [[dic objectForKey:@"lat"]stringValue];
                [self.array addObject:foodModel];
               
                if (self.nextPage == 1) {
                    //将数据库添加到数据库
                    [[FoodCitySql sharDataHandel]insertFoodCityModel:foodModel];
                }
                [foodModel release];
        }
           
            [self.collectV reloadData];
            // 拿到当前的下拉刷新控件，结束刷新状态
            [self.collectV.footer endRefreshing];
            [self.collectV.header endRefreshing];
            [self.MBHUD hide:YES];

            
        }
        
       

    }];
    
}



-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{

    return 1;

}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{

    return self.array.count;
    

}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

    
   
    self.cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuser" forIndexPath:indexPath];
    
    self.cell.contentView.backgroundColor = [UIColor whiteColor];
    
 
    FoodCityModle *foodCM = [self.array objectAtIndex:indexPath.row];
    
   self.cell.foodCM = foodCM;

    self.cell.foodCM.num = indexPath.row;
   
    self.cell.MyDelegate = self;
    
    return self.cell;

}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

    [self.MyDelegate BringPicButton];
    NewFoodDetailViewController *foodDVC = [[NewFoodDetailViewController alloc]init];
    [self.navigationController pushViewController:foodDVC animated:YES];
    
    foodDVC.indexPath = indexPath;
    
    foodDVC.array = self.array;
    
}


-(void)bringButton2:(NSInteger)num1{
    [self.MyDelegate BringUserButton];
    UserDetailViewController *userVC = [[UserDetailViewController alloc]init];
    [self.navigationController pushViewController:userVC animated:YES];
    
    FoodCityModle *foodCM = [self.array objectAtIndex:num1];
    
    
    
    userVC.user_id = foodCM.user_id;
 
    [userVC release];

}

-(void)dealloc{

    [_array release];
    [_collectV release];
    [_cell release];
    [_MBHUD release];
    [super dealloc];

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
